import { getProp } from '@/components/cms/utils'
import { RadioGroup, type RadioGroupProps } from 'ant-design-vue'
import { defineComponent, nextTick, onMounted, ref, type PropType } from 'vue'
import { formState } from '../mixins/useState'
import type { JsonSchema, Slots } from '../types'

export default defineComponent({
  inheritAttrs: true,
  emits: ['valueChange'],
  props: {
    schema: {
      type: Object as PropType<JsonSchema>,
      default: () => ({})
    },
    slots: {
      type: Object as PropType<Slots>,
      default: () => undefined
    }
  },
  setup(props, ctx) {
    const attrs = { ...props.schema.props } as RadioGroupProps
    const selected = ref<string | number | undefined>(undefined)
    const handleChange = () => {
      if (!props.schema.field) {
        console.warn('字段没有传递')
        return
      }
      const value = {
        path: props.schema.field,
        value: selected.value
      }
      ctx.emit('valueChange', value)
    }

    onMounted(() => {
      nextTick(() => {
        const value = getProp(formState.model, props.schema.field as string).value as number
        selected.value = value
      })
    })
    return () => {
      if (props.schema?.custom) {
        return (
          <RadioGroup
            onChange={() => handleChange()}
            class="custom"
            v-model={[selected.value, 'value']}
            options={undefined}
            {...attrs}
            v-slots={{ ...props?.slots }}
          ></RadioGroup>
        )
      }
      if (props.schema?.iconTemplate) {
        return (
          <RadioGroup
            onChange={() => handleChange()}
            v-model={[selected.value, 'value']}
            {...attrs}
            v-slots={{ ...props?.slots }}
          ></RadioGroup>
        )
      }
      if (!attrs?.options) {
        throw new Error('Schema props 必须包含 [options] 属性')
      }
      return (
        <RadioGroup
          onChange={() => handleChange()}
          v-model={[selected.value, 'value']}
          {...attrs}
          options={attrs!.options}
        ></RadioGroup>
      )
    }
  }
})
